package juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 *
 *
 * 3-2+3=4
 * 4-2+3=5
 *
 */
public class Semaphore {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        java.util.concurrent.Semaphore semaphore = new java.util.concurrent.Semaphore(3); //配置只能发布3个运行许可证
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire(2); //获取3个运行许可，如果获取不到会一直等待，使用tryAcquire则不会等待
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "------" + finalI);
                    semaphore.release(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }
}
